package com.mytomcat.catalina.service;

import com.mytomcat.catalina.connector.Connector;
import com.mytomcat.catalina.container.Container;
import com.mytomcat.catalina.lifecycle.LifeCycleBase;
import com.mytomcat.catalina.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 标准Service
 *
 * @author supu
 * @date 2019-04-22 10:39
 **/
public class StandardService extends LifeCycleBase implements Service {
    private static final Logger LOGGER = LoggerFactory.getLogger(StandardService.class);

    private Server server;

    private Connector[] connectors = new Connector[0];
    private final Object connectorsLock = new Object();

    private Container container;

    @Override
    protected void startInternal() {
        LOGGER.info("StandardService start");

        container.start();

        // 启动所有的connector
        synchronized (connectorsLock) {
            for (Connector connector : connectors) {
                connector.start();
            }
        }
    }

    @Override
    protected void stopInternal() {
        LOGGER.info("StandardService stop");
    }

    @Override
    protected void destroyInternal() {
        LOGGER.info("StandardService destroy");
    }

    @Override
    public void setServer(Server server) {
        this.server = server;
    }

    @Override
    public Server getServer() {
        return server;
    }

    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }

    public void addConnector(Connector connector) {
        connector.setService(this);

        synchronized (connectorsLock) {
            Connector[] newConnectors = new Connector[connectors.length + 1];
            System.arraycopy(connectors, 0, newConnectors, 0, connectors.length);
            newConnectors[connectors.length] = connector;

            connectors = newConnectors;
        }
    }
}
